<?php


namespace App\Http\Controllers\Asset;


use App\Models\Asset;
use App\Models\AssetCategory;
use App\Models\AssetStatus;
use App\Models\AssetStock;
use App\Models\FilterableAssetBundle\FilterableAssetBundleCriterion;
use Illuminate\Support\Str;

trait FilterableBundleCriterionTrait
{

    public function getCriterionQueryByFilterableAssetBundleId($id)
    {
        $criterion = FilterableAssetBundleCriterion::findOrFail($id);
        $model = $criterion->asset_type;
        $fieldName = $criterion->field_name;
        $value = $criterion->field_value;
        $operator = $criterion->operator;
        if (Str::contains($operator, 'like')) {
            $value = '%' . $value . '%';
        }
        $query = $model::where($fieldName, $operator, $value);
        if ($fieldName == "category") {
            $categoryIds = AssetCategory::where("name", $operator, $value)->select("id")->get()->pluck("id");
            $query = $model::whereIn("category_id", $categoryIds)->orWhereIn("sub_category_id", $categoryIds);
        }
        if ($model == Asset::class) {
            $query = $query->where("status_id", AssetStatus::AVAILABLE);
        }
        if ($model == AssetStock::class) {
            $query = $query->where("available_quantity", '>', 0);
        }
        return $query;
    }

}
